﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Office.Word.Server.Conversions;
using Microsoft.SharePoint;
using System.Net;
using Microsoft.SharePoint.Utilities;

namespace CodeCounsel.StateReports
{
    class ReportConverter
    {
        public SPDocumentLibrary WorkingLibrary { get; private set; }
        public SPWeb Site { get; private set; }
        //public WebClient Client { get; private set; }
        public ConversionJob Job { get; private set; }
        public SaveFormat SaveFormat { get; private set; }

        public ReportConverter(SPWeb site, SPDocumentLibrary workingList, SaveFormat saveFormat)
        {
            Site = site;
            WorkingLibrary = workingList;
            SaveFormat = saveFormat;

            ConversionJobSettings settings = new ConversionJobSettings()
            {
                OutputFormat = saveFormat
            };
            Job = new ConversionJob("Word Automation Services", settings);
            Job.UserToken = Site.CurrentUser.UserToken;
        }

        public void AddFile(string fileBaseName, byte[] contents)
        {
            string fileName = fileBaseName + ".docx";
            SPFile file = WorkingLibrary.RootFolder.Files.Add(fileName, contents);
            string conversionTargetUrl =
                SPUrlUtility.CombineUrl(
                    Site.Site.MakeFullUrl(WorkingLibrary.RootFolder.ServerRelativeUrl),
                    String.Format("{0}.{1}", fileBaseName, SaveFormat.ToString()));

            Job.AddFile(Site.Site.MakeFullUrl(file.ServerRelativeUrl), 
                conversionTargetUrl);
        }
    }
}
